import 'package:flutter/material.dart';
import 'package:manual/pages/layout_page.dart';
import 'package:manual/providers/image_list_provider.dart';
import 'package:provider/provider.dart';
import 'dart:math';
import 'package:pull_to_refresh/pull_to_refresh.dart';

/* 
RefreshListPage 使用了原生 ListView  
RefreshPullPage 使用 pull_to_refresh  大概三年前 新的插件后续也会用几个

滚动监听：SmartRefresher 会监听 ListView 或其他 ScrollView 的滚动状态和位置，判断用户是否拖动到顶部或底部。
触发条件：
  下拉刷新：
    用户在滚动容器的顶部时继续向下拖动，触发 onRefresh。
    拖动的距离达到设定的阈值（通常由 header 的高度决定）。
  上拉加载：
    用户滚动到容器的底部并继续向上拖动时，触发 onLoading。
    拖动的距离达到设定的阈值。
    这些逻辑已经由 SmartRefresher 的内部实现处理，因此你无需手动计算滚动偏移量。


触底的逻辑
  - 重置 加载完成的标记 isFinished   LoadStatus 状态
  使用 loadComplete() 表示加载完成。
  使用 loadNoData() 表示没有更多数据。
  RefreshController 触发这两个方法 就会变更 LoadStatus 状态


 */



class RefreshPullPage extends StatefulWidget {
  const RefreshPullPage({super.key});

  @override
  State<RefreshPullPage> createState() => _RefreshPullPageState();
}

class _RefreshPullPageState extends State<RefreshPullPage> {
  final RefreshController _refreshController = RefreshController(initialRefresh: false);
  List<int> items = List.generate(20, (index) => index);
  final int _maxDataLength = 30; // 数据的最大长度
  bool isFinished = false; // 是否加载完毕

  
  void _onRefresh() async {
    _refreshController.loadComplete();
    setState(() {
      isFinished = false;
    });
    final provider = context.read<ImageListProvider>();
    // 模拟加载数据
    await Future.delayed(const Duration(seconds: 2));
    final random = Random();
      final newPaths = List.generate(
        10,
        (index) => {
          "path": "lib/assets/images/common/img_${(random.nextInt(4) + 1)}.png",
          "id": "$index",
        },
      );

    provider.setImages(newPaths); // 替换现有数据
    _refreshController.refreshCompleted();
  }

  void _onLoading() async {
    if(isFinished){
      return;
    }
    final provider = context.read<ImageListProvider>();
    // 模拟加载更多数据
    await Future.delayed(const Duration(seconds: 2));
    final random = Random();
    final newPaths = List.generate(
      10,
      (index) => "lib/assets/images/common/img_${(random.nextInt(4) + 1)}.png",
    );
    // 调用 provider.addImage 方法
    for (final path in newPaths) {
      provider.addImage(path);
    }
    if(provider.imgList.length < _maxDataLength){
      _refreshController.loadComplete();
    }else{
      setState(() {
        isFinished = true;
      });
      _refreshController.loadNoData();
    }
    
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Pull to Refresh Example')),
      body: Consumer<ImageListProvider>(builder: (context, provider, child) {
        return SmartRefresher(
          controller: _refreshController,
          enablePullDown: true,
          enablePullUp: true,
          header: CustomHeader(
            builder: (BuildContext context, RefreshStatus? status) {
              Widget content;
              // 根据状态显示不同的动画
              if (status == RefreshStatus.idle) {
                content = const Center(child: Text("下拉刷新"));
              } else if (status == RefreshStatus.canRefresh) {
                content = const Center(child: Text("释放刷新"));
              } else if (status == RefreshStatus.refreshing) {
                content = const Center(child: CircularProgressIndicator(strokeWidth: 2));
              } else if (status == RefreshStatus.completed) {
                content = const Center(child: Text("刷新完成~"));
              } else {
                content = const Center(child: Text(""));
              }
              return Padding(padding: const EdgeInsets.only(top: 8 ,bottom: 8) , child: content);
            },
          ),
          footer: CustomFooter(
          builder: (BuildContext context, LoadStatus? status) {
            Widget content;
            if (status == LoadStatus.idle) {
              content = const Text("Pull up to load more");
            } else if (status == LoadStatus.loading) {
              content = const CircularProgressIndicator(
                strokeWidth: 2.0,
                color: Colors.blue,
              );
            } else if (status == LoadStatus.failed) {
              content = const Text("Load failed! Tap to retry.");
            } else if (status == LoadStatus.canLoading) {
              content = const Text("Release to load more");
            } else if (status == LoadStatus.noMore) {
              content = const Text("No more data");
            } else {
              content = const SizedBox.shrink();
            }
            // 添加样式（如边距、对齐方式等）
            return Padding(
              padding: const EdgeInsets.symmetric(vertical: 8.0), // 上下间距
              child: Center(child: content),
            );
          },
        ),
          onRefresh: _onRefresh,
          onLoading: _onLoading,
          child: ListView.builder(
            itemCount: provider.imgList.length,
            itemBuilder: (context, index) {
              final imgData = provider.imgList[index];
              return ImageLayout(path: imgData["path"] ?? "", id: imgData["id"] ?? "");
            },
          ),
        );
      })
    );
  }
}
